import pandas as pd
import os

# 基础路径
base_path = 'D:\\Desktop\\Electric_Vehicle_Crawler\\crawler\\新能源\\处理过的评论'

# 品牌列表
brands = ['比亚迪', '大众', '丰田', '广汽埃安', '理想', '奇瑞', '特斯拉', '蔚来', '五菱汽车', '长安']

# 遍历所有品牌
for brand in brands:
    brand_excel_folder = os.path.join(base_path, brand)

    # 初始化一个字典来存储所有品牌的拼接评论
    brand_comments = {}

    # 遍历品牌Excel文件夹中的所有Excel文件
    for file_name in os.listdir(brand_excel_folder):
        if file_name.endswith('.xlsx'):
            file_path = os.path.join(brand_excel_folder, file_name)

            # 读取Excel文件内容
            df = pd.read_excel(file_path)

            # 提取评论和次数
            comments = []
            for _, row in df.iterrows():
                comment = row['评论']
                count = row['出现次数']
                comments.extend([comment] * count)

            # 拼接评论字符串
            file_base_name = os.path.splitext(file_name)[0]  # 获取文件名去掉扩展名
            brand_comments[file_base_name] = '/'.join(comments)

    # 将拼接后的评论保存到txt文件中
    for file_base_name, comments in brand_comments.items():
        output_file_path = os.path.join(brand_excel_folder, f'{file_base_name}.txt')
        with open(output_file_path, 'w', encoding='utf-8') as f:
            f.write(comments)

print("评论拼接完成并保存到txt文件中。")
